package com.maya.bluetooth;


import com.maya.R;
import com.maya.screens.Constants;
import com.maya.utilities.Utilities;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.InputFilter;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This is the main Activity that displays the current chat session.
 */
public class Bluetooth extends Activity implements OnClickListener
{
    // Debugging
    private static final String TAG = "Bluetooth";
    private static final boolean D = true;

    // Message types sent from the BluetoothService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;

    // Key names received from the BluetoothService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";

    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
    private static final int REQUEST_ENABLE_BT = 2;

    // Layout Views
    private ListView mMyGuessesView;
    private ListView mYourGuessesView;
    private EditText mGuess;
    private TextView mBulunmasiIstenenAlertBuilderText;
    private TextView mBulunmasiIstenenView;
    
    private Button mTryButton;

    // Name of the connected device
    private String mConnectedDeviceName = null;
    // Array adapter for the conversation thread
    private ArrayAdapter<String> mMyConversationArrayAdapter;
    private ArrayAdapter<String> mYourConversationArrayAdapter;
    // String buffer for outgoing messages
    private StringBuffer mOutStringBuffer;
    // Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;
    // Member object for the chat services
    private BluetoothService mGameService = null;
    
    Utilities util = new Utilities();
    private Resources res;
    
    private boolean mOyunBaslayabilir;
    private int bulunmasiIstenen;
    int[] bulunmasiIstenenSayi = new int[4];
    int[] thmn = new int[4];
    int kullanici_tahmini = -1;
    static int dogru_yer = 0;
	static int dogru_sayi = 0;
	static int tahmin_sayisi = 0;


    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        if(D) Log.e(TAG, "+++ ON CREATE +++");

        // Set up the window layout
        setContentView(R.layout.bt_main);
        
        res = this.getResources();
             
        //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
   
        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
       
        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) 
        {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }      
    }

    @Override
    public void onStart() 
    {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");

        // If BT is not on, request that it be enabled.
        if (!mBluetoothAdapter.isEnabled()) 
        {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        
        }// Otherwise, setup the game session
        else 
        {
            if (mGameService == null)
            {
            	setupGame();            	
            }
        }
    }

    @Override
    public synchronized void onResume() 
    {
        super.onResume();
        if(D) Log.e(TAG, "+ ON RESUME +");

        // Performing this check in onResume() covers the case in which BT was not enabled during onStart(), 
        // so we were paused to enable it... onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (mGameService != null) 
        {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mGameService.getState() == BluetoothService.STATE_NONE) {
              // Start the Bluetooth chat services
              mGameService.start();
            }
        }
    }

    private void setupGame() 
    {
        Log.d(TAG, "setupGame()");

        // Initialize the array adapter for the conversation thread
        mMyConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.bt_message);
        mYourConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.bt_message);
        mMyGuessesView = (ListView) findViewById(R.id.inMine);
        mMyGuessesView.setAdapter(mMyConversationArrayAdapter);  
        mYourGuessesView = (ListView) findViewById(R.id.inYours);
        mYourGuessesView.setAdapter(mYourConversationArrayAdapter);

        // Initialize the compose field with a listener for the return key
        mGuess = (EditText) findViewById(R.id.editTextGuess);
        mGuess.setOnEditorActionListener(mWriteListener);

        // Initialize the send button with a listener that for click events
        mTryButton = (Button) findViewById(R.id.buttonTry);
        mTryButton.setOnClickListener(this);
        
        mBulunmasiIstenenView = (TextView) findViewById(R.id.editTextBulunmasiIstenen);
       
        // Initialize the BluetoothService to perform bluetooth connections
        mGameService = new BluetoothService(this, mHandler);

        // Initialize the buffer for outgoing messages
        mOutStringBuffer = new StringBuffer("");
    }

    @Override
    public synchronized void onPause() 
    {
        super.onPause();
        if(D) Log.e(TAG, "- ON PAUSE -");
    }

    @Override
    public void onStop() 
    {
        super.onStop();
        if(D) Log.e(TAG, "-- ON STOP --");
    }

    @Override
    public void onDestroy() 
    {
        super.onDestroy();
        // Stop the Bluetooth chat services
        if (mGameService != null) mGameService.stop();
        if(D) Log.e(TAG, "--- ON DESTROY ---");
    }

    private void ensureDiscoverable() 
    {
        if(D) Log.d(TAG, "ensure discoverable");
        if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) 
        {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }

    /**
     * Sends a message.
     * @param message  A string of text to send.
     */
    private void sendMessage(String message) 
    {
        // Check that we're actually connected before trying anything
        if (mGameService.getState() != BluetoothService.STATE_CONNECTED) 
        {
            Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
            return;
        }
        if (mOyunBaslayabilir)
        {
	        // Check that there's actually something to send
	        if (message.length() > 0) 
	        {
	            // Get the message bytes and tell the BluetoothService to write
	            byte[] send = message.getBytes();
	            mGameService.write(send);
	
	            // Reset out string buffer to zero and clear the edit text field
	            mOutStringBuffer.setLength(0);
	            mGuess.setText(mOutStringBuffer);
	        }
        }
        else
        {
        	 Toast.makeText(this, "Bulunmasi istenen sayıyı girmediniz", Toast.LENGTH_SHORT).show();				
        }
    }

    // The action listener for the EditText widget, to listen for the return key
    private TextView.OnEditorActionListener mWriteListener =
        new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            // If the action is a key-up event on the return key, send the message
            if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
                String message = view.getText().toString();
                sendMessage(message);
            }
            if(D) Log.i(TAG, "END onEditorAction");
            return true;
        }
    };

    private final void setStatus(int resId) {
        final ActionBar actionBar = getActionBar();
        actionBar.setSubtitle(resId);
    }

    private final void setStatus(CharSequence subTitle) {
        final ActionBar actionBar = getActionBar();
        actionBar.setSubtitle(subTitle);
    }

    // The Handler that gets information back from the BluetoothService
    private final Handler mHandler = new Handler() 
    {
        @Override
        public void handleMessage(Message msg) 
        {
            switch (msg.what) 
            {
	            case MESSAGE_STATE_CHANGE:
	                if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
		                switch (msg.arg1) 
		                {
			                case BluetoothService.STATE_CONNECTED:
			                    setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
			                    mMyConversationArrayAdapter.clear();
			                    mYourConversationArrayAdapter.clear();
			                    getTahminEdilecekSayi();
			                    break;
			                case BluetoothService.STATE_CONNECTING:
			                	setStatus(R.string.title_connecting);
			                    break;
			                case BluetoothService.STATE_LISTEN:
			                case BluetoothService.STATE_NONE:
			                    setStatus(R.string.title_not_connected);
			                    break;
		                }
	                break;
	            case MESSAGE_WRITE:
	                byte[] writeBuf = (byte[]) msg.obj;
	                // construct a string from the buffer
	                String writeMessage = new String(writeBuf);
	                break;
	            case MESSAGE_READ:
	                byte[] readBuf = (byte[]) msg.obj;
	                // construct a string from the valid bytes in the buffer
	                String readMessage = new String(readBuf, 0, msg.arg1);
	                
	                if(readMessage.charAt(0)=='X')
	                {
	                	mMyConversationArrayAdapter.add(readMessage.substring(1, readMessage.length()));
	                }
	                else if(readMessage.charAt(0)=='W')
	                {
	                	oyunBitir(true);	
	                }	                
	                else
	                {
	                	checkGuess(readMessage);
	                }
	                
	                
	                
	                break;
	            case MESSAGE_DEVICE_NAME:
	                // save the connected device's name
	                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
	                Toast.makeText(getApplicationContext(), "Connected to "
	                               + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
	                break;
	            case MESSAGE_TOAST:
	                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
	                               Toast.LENGTH_SHORT).show();
	                break;
            }
        }		
    };

    public void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        if(D) Log.d(TAG, "onActivityResult " + resultCode);
        switch (requestCode) 
        {
	        case REQUEST_CONNECT_DEVICE_SECURE:
	            // When DeviceListActivity returns with a device to connect
	            if (resultCode == Activity.RESULT_OK) 
	            {
	                connectDevice(data, true);       	
	            }
	            break;
	        case REQUEST_ENABLE_BT:
	            // When the request to enable Bluetooth returns
	            if (resultCode == Activity.RESULT_OK) 
	            {
	                // Bluetooth is now enabled, so set up a game session
	                setupGame();
	            } 
	            else 
	            {
	                // User did not enable Bluetooth or an error occurred
	                Log.d(TAG, "BT not enabled");
	                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
	                finish();
	            }
	            break;
	        default:
	        	break;
	        	
        }
    }

	private void connectDevice(Intent data, boolean secure) 
    {
        // Get the device MAC address
        String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
        
        // Get the BluetoothDevice object
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        // Attempt to connect to the device
        mGameService.connect(device, secure);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
        Intent serverIntent = null;
        switch (item.getItemId()) 
        {
	        case R.id.secure_connect_scan:
	            // Launch the DeviceListActivity to see devices and do scan
	            serverIntent = new Intent(this, DeviceListActivity.class);
	            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
	            return true;
	            
	        case R.id.discoverable:
	            // Ensure this device is discoverable by others
	            ensureDiscoverable();
	            return true;
	        	
	    }
	    return false;
    }
    
	
	private void getTahminEdilecekSayi() 
	{	
		LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE );
		View layout = inflater.inflate(R.layout.alertbuilder, null);
	
		mBulunmasiIstenenAlertBuilderText = (TextView) layout.findViewById(R.id.numberWanted2Find);
		mBulunmasiIstenenAlertBuilderText.requestFocus();
		mBulunmasiIstenenAlertBuilderText.setText("");
        InputFilter[] FilterArray = new InputFilter[1];
        FilterArray[0] = new InputFilter.LengthFilter(4);
        mBulunmasiIstenenAlertBuilderText.setFilters(FilterArray);
        AlertDialog.Builder builder = new AlertDialog.Builder(Bluetooth.this);
		builder.setTitle("");
		builder.setMessage(R.string.enterNumberWanted2Find);
		builder.setIcon(R.drawable.question);
		builder.setView(layout);
		
		builder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() 
		{		
			public void onClick(DialogInterface dialog, int which) 
			{
				bulunmasiIstenen = Integer.parseInt(mBulunmasiIstenenAlertBuilderText.getText().toString());
				
				bulunmasiIstenenSayi[0] = (int)(bulunmasiIstenen/1000);
				bulunmasiIstenenSayi[1] = (int)((bulunmasiIstenen%1000)/100);
				bulunmasiIstenenSayi[2] = (int)((bulunmasiIstenen%100)/10);
				bulunmasiIstenenSayi[3] = (bulunmasiIstenen%10);
				
				if((bulunmasiIstenenSayi[0]==0
						||bulunmasiIstenenSayi[0]==bulunmasiIstenenSayi[1]
						||bulunmasiIstenenSayi[0]==bulunmasiIstenenSayi[2]
						||bulunmasiIstenenSayi[0]==bulunmasiIstenenSayi[3]
						||bulunmasiIstenenSayi[1]==bulunmasiIstenenSayi[2]
						||bulunmasiIstenenSayi[1]==bulunmasiIstenenSayi[3]
						||bulunmasiIstenenSayi[2]==bulunmasiIstenenSayi[3]))
				{
					util.showToast(getApplicationContext(),R.string.ErrorInputGuess, 2000, Constants.ERROR_ICON_ID);			
				}
				else
				{
					mOyunBaslayabilir = true;
					
					mBulunmasiIstenenView.setText("Bulunmasini istediğiniz sayı:"+bulunmasiIstenen);
				}
				
			}
		});
		
		builder.setNegativeButton(R.string.Cancel, new DialogInterface.OnClickListener()
		{			
			public void onClick(DialogInterface dialog, int which) 
			{
				
			}
		});
		
		AlertDialog alert = builder.create();
		alert.show();
		
	}
	
	public void onClick(View v) 
	{
		if(v == mTryButton) 
		{	
			String message = mGuess.getText().toString();
			sendMessage(message);
		}       	
	}
	
	protected void checkGuess(String readMessage)
	{
		kullanici_tahmini = Integer.parseInt(readMessage);
		
		thmn[0] = (int)(kullanici_tahmini/1000);
		thmn[1] = (int)((kullanici_tahmini%1000)/100);
		thmn[2] = (int)((kullanici_tahmini%100)/10);
		thmn[3] = (kullanici_tahmini%10);

		if((thmn[0]==0
				||thmn[0]==thmn[1]||thmn[0]==thmn[2]||thmn[0]==thmn[3]
				||thmn[1]==thmn[2]||thmn[1]==thmn[3]||thmn[2]==thmn[3]))		
		{
			util.showToast(getApplicationContext(),R.string.ErrorInputGuess, 2000, Constants.ERROR_ICON_ID);
		}
		else
		{
			tahmin_sayisi++;
						
			for(int i = 0; i<4; i++)
			{
				for(int j = 0; j<4; j++)
				{
					if((bulunmasiIstenenSayi[i] == thmn[j]) && (i==j))
					{
						dogru_yer++;
						break;
					}
								
					if((bulunmasiIstenenSayi[i]==thmn[j]) && (i!=j))
					{
						dogru_sayi++;
						break;
					}
				}						
			}
				
			String s = res.getString(R.string.nThGuess);
			String sonuc ="";
			
			if(dogru_yer==0 && dogru_sayi==0)
				sonuc = tahmin_sayisi+s+" "+readMessage+"\t0\n";
			else if(dogru_yer==0 && dogru_sayi!=0)
				sonuc = tahmin_sayisi+s+" "+readMessage+"\t-"+dogru_sayi+"\n";		
			else if(dogru_yer!=0 && dogru_sayi==0)
				sonuc = tahmin_sayisi+s+" "+readMessage+"\t+"+dogru_yer+"\n";
			else if(dogru_yer!=0 && dogru_sayi!=0)
				sonuc = tahmin_sayisi+s+" "+readMessage+"\t+"+dogru_yer+"  "+"-"+dogru_sayi+"\n";
							
			
			mYourConversationArrayAdapter.add(mConnectedDeviceName+":"+sonuc);
			sendMessage("X"+sonuc);
			
			if(dogru_yer==4)
			{
				oyunBitir(false);	
				sendMessage("W");
			}
				
			dogru_yer = 0;
			dogru_sayi = 0;
		}
	}
	
	public void oyunBitir(boolean win)
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(Bluetooth.this);
		builder.setTitle("");
		builder.setCancelable(false);
		
		if(win)
		{
			//util.showToast(getApplicationContext(),R.string.winGame, 1000, Constants.STAR_ICON_ID);
			builder.setMessage(R.string.bt_win_game);
			builder.setIcon(R.drawable.star);
		}
		else
		{
			//util.showToast(getApplicationContext(),R.string.lostGame, 1000, Constants.SADNESS_ICON_ID);
			builder.setMessage(R.string.bt_lost_game);
			builder.setIcon(R.drawable.sadness);
		}
		
		
		builder.setPositiveButton(R.string.Yes, new DialogInterface.OnClickListener() 
		{		
			public void onClick(DialogInterface dialog, int which) 
			{
						
			}
		});
		
		builder.setNegativeButton(R.string.No, new DialogInterface.OnClickListener()
		{			
			public void onClick(DialogInterface dialog, int which) 
			{
				
			}
		});
		
		AlertDialog dialog = builder.create();
		dialog.show();
	}
	

}
